#!/usr/bin/env python
# -*- coding: utf-8 -*-


from cryptography.fernet import Fernet
from sanic.request import json_loads
from sanic.response import json_dumps
from decimal import Decimal
from datetime import datetime, date
import hashlib
from conf import conf
import pickle

def jsonify(records):
    return [dict(r.items()) for r in records]

def set_auth_cookies(token,cookies):
    '''
    加密cookies
    :param token:
    :param cookies:
    :return:
    '''
    f = Fernet(token)
    cookies_json = json_dumps(cookies)
    token = f.encrypt(cookies_json.encode())
    cookies_json = token.decode()
    return cookies_json

def get_auth_cookies(token, cookies):
    '''
    解密cookies
    :param token:
    :param cookies:
    :return:
    '''
    if isinstance(token,bytes):
        token = token.decode('utf-8')
    f = Fernet(token)
    cookie_json = f.decrypt(cookies.encode()).decode()
    cookies_data = json_loads(cookie_json)
    return cookies_data


class Utils(object):
    import json
    @staticmethod
    def JSONEncoder():
        class JSONEncoder(json.JSONEncoder):
            def default(self, obj):
                if isinstance(obj, Decimal):
                    return float(obj)
                if isinstance(obj, datetime):
                    return str(obj)
                if isinstance(obj, date):
                    return str(obj)
                try:
                    return obj.tojson()
                except AttributeError:
                    return json.JSONEncoder.default(self, obj)
        return JSONEncoder

    @staticmethod
    def md5(str):
        m2 = hashlib.md5()
        m2.update("{str}".format(str=str).encode("utf-8"))
        return m2.hexdigest()

    @staticmethod
    def _compute_key(function, args, kw):
        key = pickle.dumps((function.__name__, args, kw))
        return hashlib.sha1(key).hexdigest()

    @staticmethod
    def get_key(key):
        """ 拼装 redis key """
        return "{prefix}{key}".format(prefix=conf.redis.prefix, key=key)

    @staticmethod
    def current_time(format='%Y-%m-%d %H:%M:%S'):
        return datetime.strftime(format,datetime.now())
